package com.think.provider;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2018/5/23 0023.
 */
@Component
public class WebAuthenticationProvider extends DaoAuthenticationProvider {

    public WebAuthenticationProvider(UserDetailsService userDetailsService) {
        super();
        // 这个地方一定要对userDetailsService赋值，不然userDetailsService是null (这个坑有点深)
        super.setUserDetailsService(userDetailsService);
    }

    @Override
    @SuppressWarnings("deprecation")
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        Object salt = null;
        if (this.getSaltSource() != null) {
            salt = this.getSaltSource().getSalt(userDetails);
        }
        if (authentication.getCredentials() == null) {
            logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
        //我就改了这个地方，增加一个验证码登录标识(具体怎么做就看自己了)
        //【原本的是登录密码和数据密码不等就抛出异常，我用验证码登录时压根都不知道密码
        // so 我给短信登录时赋值一个默认密码（验证码登录标识）来判断，不让这儿报异常
        String presentedPassword = authentication.getCredentials().toString();
        String password = userDetails.getPassword();
        if (null != password && password.length() > 0) {
            if(!BCrypt.checkpw(presentedPassword, password)) {
                logger.debug("Authentication failed: password does not match stored value");
                throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        }

//            if (!getPasswordEncoder().isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
//                logger.debug("Authentication failed: password does not match stored value");
//                throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
//            }
    }
}
